<template>
	<div class="affix-box">
		<div ref="affix">
			<slot />
		</div>
	</div>
</template>

<script>
	export default {
		props: {
			box: {
				type: String,
				default: 'uni-page-body'
			},
			position: String,
			offset: Number
		},
		data() {
			return {
				affix: null,
				affixOffset: null,
				affixBoxOffset: null,
				affixBox: null,
				affixScroll: null
			};
		},
		methods: {
			handleScroll() {
				this.affixBoxOffset = this.affixBox.getBoundingClientRect();
				if (this.position == 'bottom' && this.affixBoxOffset.top + this.affixOffset.height - document.body
					.clientHeight > -this.offset) {
					this.affix.style.position = 'fixed';
					this.affix.style.zIndex = '2000';
					this.affix.style.bottom = this.offset + 'px';

					this.affixBox.style.width = this.affixOffset.width + 'px';
					this.affixBox.style.height = this.affixOffset.height + 'px';
				} else if (this.position == 'top' && this.affixOffset.top - this.affixScroll.scrollTop - this
					.affixScrollTop <= this.offset) {
					this.affix.style.position = 'fixed';
					this.affix.style.zIndex = '2000';
					this.affix.style.top = this.affixScrollTop + this.offset + 'px';

					this.affixBox.style.width = this.affixOffset.width + 'px';
					this.affixBox.style.height = this.affixOffset.height + 'px';
				} else {
					this.affix.style.position = 'initial';
					this.affix.style.top = 'initial';
				}
			},
			getAffixScrollBox() {
				this.affixScroll = document.querySelector(this.box);
				this.affixScrollTop = this.affixScroll.getBoundingClientRect().top;

				this.handleScroll();
			}
		},
		mounted() {
			this.affix = this.$refs.affix;
			this.affixOffset = this.affix.getBoundingClientRect();

			this.affixBox = this.affix.parentElement;
			this.affixBoxOffset = this.affixBox.getBoundingClientRect();

			this.affixScroll = document.querySelector(this.box);
			this.affixScrollTop = this.affixScroll.getBoundingClientRect().top;

			this.affixScroll.addEventListener('scroll', this.handleScroll, true);
			this.$nextTick(() => {
				this.handleScroll();
			});
		}
	};
</script>

<style></style>
